package com.lepu.app.fun.my;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import lib.share.utils.CallBack;
import lib.share.utils.ShareLib;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.app.utils.AppEnterTongJi;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.ObserverConst;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserLocaljsObject.BrowserLocaljsObjectDelegate;
import com.core.lib.utils.BrowserLocaljsObject;
import com.core.lib.utils.BrowserWebChromeClient;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.BrowserWebChromeClient.BrowserWebChromeDelegate;
import com.core.lib.utils.BrowserWebClient;
import com.core.lib.utils.BrowserWebClient.BrowserWebClientDelegate;
import com.core.lib.utils.Observer;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.CustomWebView;
import com.eyzhs.app.R;
import com.lepu.app.fun.index.activity.IndexWriterCommentActivity;
import com.lepu.app.fun.my.bean.BeanCollectKnowledge;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

/**
 * 
 * @author wxd
 * 
 */
public class MyArticleInfoWriterActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, BrowserWebChromeDelegate,
		BrowserWebClientDelegate, AsyncRequest, BrowserLocaljsObjectDelegate, Observer{

	// sample request
	private static final String REQUEST_TEST = "request_test";
	private static final String REQUEST_FAVOR = "request_favor";

	private static final int MSG_COMMETN = 11;
	private static final int MSG_FAVOR = 12;
	private static final int MSG_FAVOR_IS = 13;
	private static final int MSG_COLLECT = 14;
	
	private CustomWebView mWebView = null;
	private ProgressBar mProgressBar = null;

	private CustomTopBarNew mTopbar = null;
	
	private TextView mCommentTextView;
	private TextView mFavorTextView;
	private ImageView mFavorImageView;
	private ImageView mCollectImageView;
 
	// 外边传入
	private String mTargetID = "";

	// 自己赋值
	private String mShareTitle = "";
	private String mShareUrl = "";
	private String mShareInfo = "";
	private String mShareCover = "";
	
	private int mJsCount=1;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_article_info_writer_activity);

		init();
		ObserverManager.getInstance().addObserver(ObserverConst.NOTIFY_WRITER_COMMENT_CHANGE_INFO, this);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onResume() {
		mWebView.onResume();
		super.onResume();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onPause() {
		mWebView.onPause();
		super.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		if(mWebView != null)
		{
			try {
				mWebView.removeAllViews();
				mWebView.destroy();
				
				LinearLayout contentLayout = (LinearLayout) findViewById(R.id.contentLayout);
				contentLayout.removeView(mWebView);
			} catch (Exception e) {
				android.util.Log.d("错误 220 行", "webview Exception");
			}
		}
		
		ObserverManager.getInstance().removeObserver(ObserverConst.NOTIFY_WRITER_COMMENT_CHANGE_INFO);
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		closePage();
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	private void closePage() {
		if (mWebView.canGoBack()) {
			mWebView.goBack();

			// mTopbar.setTopbarTitle(mTopbarTitle);
			return;
		}

		finish(true);
	}

	/**
	 * 初始化方法
	 */
	@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
	private void init() {
		mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
		mTopbar.setTopbarTitle("");
		mTopbar.setonTopbarNewLeftLayoutListener(this);

		mTopbar.setTopbarTitle("");

		mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);

		mWebView = (CustomWebView) findViewById(R.id.webView);
		mWebView.setWebChromeClient(new BrowserWebChromeClient(this));
		mWebView.setWebViewClient(new BrowserWebClient(this, this, mWebView));
		mWebView.getSettings().setJavaScriptEnabled(true);

		// js
		BrowserLocaljsObject jsObj = new BrowserLocaljsObject(this);
		mWebView.addJavascriptInterface(jsObj, "local_obj");
		mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "load_obj");
		
		mCommentTextView = (TextView) findViewById(R.id.commentTextView);
		mFavorTextView = (TextView) findViewById(R.id.favorTextView);
		mFavorImageView = (ImageView) findViewById(R.id.favorImageView);
		mCollectImageView = (ImageView) findViewById(R.id.collectImageView);
		
		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0) {
			if(data.containsKey("TargetID")){
				mTargetID = data.getString("TargetID");
			}
			
			if (data.containsKey("url")) {
				mShareUrl = data.getString("url");

				Utils.initWebViewSettings(mWebView, false);

				showWebViewUrl(mShareUrl);
			}
		}
	}

	public void showWebViewUrl(String url) {

		if (!StringUtilBase.stringIsEmpty(url)) {
			mWebView.loadUrl(url);
		}
	}

	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.commentImageView:
			Intent intent1 = new Intent(MyArticleInfoWriterActivity.this,IndexWriterCommentActivity.class);
			intent1.putExtra("ArticleID", mTargetID);
			startActivity(intent1,true);
			break;
		case R.id.favorImageView:
			if(mFavorImageView.isSelected()){
				clickFavor(0);
			}else{
				clickFavor(1);
			}
			break;
		
		case R.id.collectImageView:

			clickCollect();
			break;

		case R.id.shareImageView:

			clickShare();
			break;
		case R.id.comment_layout:
			Intent intent2 = new Intent(MyArticleInfoWriterActivity.this,IndexWriterCommentActivity.class);
			intent2.putExtra("ArticleID", mTargetID);
			startActivity(intent2,true);
			break;
		default:
			break;
		}
	}
	
	public void clickFavor(int favor){
		boolean flagLogin = MainTabActivity.jumpLogin(this);

		if (flagLogin) {
			return;
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
		    params.put("UserID", LoginUtil.getUserId());
		    params.put("LoginToken", LoginUtil.getLoginToken());
			
		    params.put("OperationType", favor);
		    params.put("ArticleID", mTargetID);
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post_main(Setting.getWriterFavorUrl(), map, null, this, REQUEST_FAVOR, true,false,true);
	}

	private void updateCollectState() {

		boolean flag = BeanCollectKnowledge.checkCollectItemArticle(
				LoginUtil.getUserId(), mTargetID,
				BeanCollectKnowledge.TYPE_ARTICLE_WRITER);
		if (flag) {
			mCollectImageView.setSelected(true);
		} else {
			mCollectImageView.setSelected(false);
		}
	}

	private void clickCollect() {

		AppEnterTongJi.clickEvent(47, mTargetID);
		
		boolean flagLogin = MainTabActivity.jumpLogin(this);

		if (flagLogin) {
			return;
		}

		String uid = LoginUtil.getUserId();
		boolean flag = BeanCollectKnowledge.checkCollectItemArticle(uid,
				mTargetID, BeanCollectKnowledge.TYPE_ARTICLE_WRITER);

		boolean updateFlag = false;
		if (flag) {
			updateFlag = BeanCollectKnowledge.deleteItemArticle(uid,mTargetID, BeanCollectKnowledge.TYPE_ARTICLE_WRITER);

			UIHelper.showToast(this, R.string.collect_cancel);
			
		} else {
			BeanCollectKnowledge item = new BeanCollectKnowledge();
			item.Uid = uid;
			item.Time = System.currentTimeMillis();

			item.Type = BeanCollectKnowledge.TYPE_ARTICLE_WRITER;
			item.Title = mShareTitle;
			item.SubTitle = mShareUrl;
			item.ArticleID = mTargetID;
			updateFlag = BeanCollectKnowledge.insertCollectItem(item);

			UIHelper.showToast(this, R.string.collect_success);
			
		}

		if (updateFlag) {
			updateCollectState();
		}
	}

	private void clickShare() {

		AppEnterTongJi.clickEvent(48, mTargetID);
		
		String cover = "";

		if (TextUtils.isEmpty(mShareCover)) {
			cover = SdLocal.getAppIconPath(getApplicationContext());
		} else {
			cover = mShareCover;
		}
		
		String shareUrl = Setting.getShareArticleUrl(mTargetID);

		// 调用官方sdk分享，可以各种形式
		ShareLib.Share(this, mShareTitle, mShareInfo, cover, shareUrl, false,
				new CallBack() {
					@Override
					public void callBackSuccess(Object obj) {
						super.callBackSuccess(obj);

						MyNetUtil.getInstance().requestShare(
								MyArticleInfoWriterActivity.this,
								MyNetUtil.getInstance(), 1, mTargetID);
					}
				});
	}

	
	
	// =====================================
	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_TEST)) {

		}else if(object.equals(REQUEST_FAVOR)){
			if(mFavorImageView.isSelected()){
				mFavorImageView.setSelected(false);
				UIHelper.showToast(MyArticleInfoWriterActivity.this, "取消点赞");
				String favorS = mFavorTextView.getText().toString();
				if(!TextUtils.isEmpty(favorS)){
					int favorI = Integer.valueOf(favorS)-1;
					if(favorI<0){
						favorI = 0;
					}
					
					mFavorTextView.setText(String.valueOf(favorI));
				}
				
			}else{
				mFavorImageView.setSelected(true);
				UIHelper.showToast(MyArticleInfoWriterActivity.this, "点赞成功");
				String favorS = mFavorTextView.getText().toString();
				if(!TextUtils.isEmpty(favorS)){
					int favorI = Integer.valueOf(favorS)+1;
					if(favorI<0){
						favorI = 0;
					}
					
					mFavorTextView.setText(String.valueOf(favorI));
				}
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_TEST)) {
		}else if(object.equals(REQUEST_FAVOR)){
			
		}
	}
	
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_COMMETN:
				String commentCount = (String) msg.obj;
				mCommentTextView.setText(commentCount);
				break;
			case MSG_FAVOR:
				String favorCount = (String) msg.obj;
				mFavorTextView.setText(favorCount);
				break;
			case MSG_FAVOR_IS:
				int favorIs = Integer.valueOf((String) msg.obj);
				
				if(favorIs == 0){
					mFavorImageView.setSelected(false);
				}else if(favorIs == 1){
					mFavorImageView.setSelected(true);
				}
				break;
			case MSG_COLLECT:
				updateCollectState();
				break;
			default:
				break;
			}
		};
	};
	

	//js回调
    final class InJavaScriptLocalObj {
    	
    	@JavascriptInterface
        public void showSource(String html) {
    		if(mJsCount == 1){
    			mJsCount++;
    			
    			Message msg = mHandler.obtainMessage();
				msg.what = MSG_COMMETN;
				msg.obj = html;
				mHandler.sendMessage(msg);
    		}else if(mJsCount == 2){
    			mJsCount++;
    			
    			Message msg = mHandler.obtainMessage();
				msg.what = MSG_FAVOR;
				msg.obj = html;
				mHandler.sendMessage(msg);
    		}else if(mJsCount == 3){
    			mJsCount++;
    			//阅读数
    		}else if(mJsCount == 4){
    			mJsCount++;
    			//是否点赞
    			Message msg = mHandler.obtainMessage();
				msg.what = MSG_FAVOR_IS;
				msg.obj = html;
				mHandler.sendMessage(msg);
    		}
    		
        }
    }
    
    //评论成功
	@Override
	public void notify(String arg0, Object arg1, Object arg2) {
		String favorS = mCommentTextView.getText().toString();
		if(!TextUtils.isEmpty(favorS)){
			int favorI = Integer.valueOf(favorS)+1;
			mCommentTextView.setText(String.valueOf(favorI));
		}
	}
	
	// ===========================================================
	public void onProgressChanged(WebView view, int newProgress) {
		LogUtilBase.LogD(null, "onProgressChanged===>>" + newProgress);

		mProgressBar.setMax(100);
		if (newProgress < 100) {
			if (mProgressBar.getVisibility() == View.GONE) {
				mProgressBar.setVisibility(View.VISIBLE);
			}
			mProgressBar.setProgress(newProgress);
		} else {
			mProgressBar.setProgress(100);

			Animation animation = AnimationUtils.loadAnimation(this,
					R.anim.lib_broswer_progress);
			// 运行动画
			mProgressBar.startAnimation(animation);
			// 将 spinner 的可见性设置为不可见状态
			mProgressBar.setVisibility(View.GONE);
		}
	}

	// ======================================
	public void onPageStarted(String url) {
		LogUtilBase.LogD(null, "onPageStarted===>>" + url);
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView webView, String url) {
		LogUtilBase.LogD(null, "shouldOverrideUrlLoading == >>" + url);
		webView.loadUrl(url);
		return true;
	}

	public void onPageFinished(String url) {
		LogUtilBase.LogD(null, "onPageFinished===>>" + url);
		mShareUrl = url;
		
		mWebView.loadUrl("javascript:window.load_obj.showSource(document.getElementById('InfoForApp').getAttribute('CommentCount'));");
		mWebView.loadUrl("javascript:window.load_obj.showSource(document.getElementById('InfoForApp').getAttribute('FavourCount'));");
		mWebView.loadUrl("javascript:window.load_obj.showSource(document.getElementById('InfoForApp').getAttribute('ViewCount'));");
		mWebView.loadUrl("javascript:window.load_obj.showSource(document.getElementById('InfoForApp').getAttribute('IsFavour'));");
	}

	// ===============================================
	@Override
	public void getHtmlLength(int arg0) {

	}

	@Override
	public void getReferrer(String arg0) {

	}

	@Override
	public void getTitle(String title) {

		if (!TextUtils.isEmpty(mShareUrl)) {
			mShareTitle = title;
		}
	}

	@Override
	public void getVideoSrc(String arg0) {

	}

	@Override
	public void getCover(String cover) {
		if (!TextUtils.isEmpty(mShareUrl)) {
			mShareCover = cover;
		}
	}

	@Override
	public void getDescription(String Description) {
		if (!TextUtils.isEmpty(mShareUrl)) {
			mShareInfo = Description;
		}
	}

	@Override
	public void getArticleID(String ArticleID) {
		if (!TextUtils.isEmpty(mShareUrl)) {
			mTargetID = ArticleID;
		}
		
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				LinearLayout rightMenuLayout = (LinearLayout) findViewById(R.id.rightMenuLayout);
				if (!TextUtils.isEmpty(mTargetID)) {
					rightMenuLayout.setVisibility(View.VISIBLE);
					updateCollectState();
				} else {
					rightMenuLayout.setVisibility(View.GONE);
				}
			}
		});
	}


}
